package com.ls.service.impl;

import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.ls.entity.DiscussPost;
import com.ls.entity.vo.DiscussPostVo;
import com.ls.mapper.DiscussPostMapper;
import com.ls.service.DiscussPostService;
import com.ls.service.LikeService;
import com.ls.service.UserService;
import com.ls.util.CommunityConstant;
import com.ls.util.SensitiveFilter;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ls
 */
@Service
public class DiscussPostServiceImpl implements DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostServiceImpl.class);

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private LikeService likeService;

    @Autowired
    private UserService userService;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    // Caffeine核心接口: Cache, LoadingCache, AsyncLoadingCache

    /**
     * 帖子列表缓存
     */
    private LoadingCache<String, List<DiscussPostVo>> postListCache;

    /**
     * 帖子总数缓存
     */
    private LoadingCache<Integer, Integer> postRowsCache;


    @Autowired
    private DiscussPostService discussPostService;

    /**
     * 功能描述: <br>
     * 初始化帖子缓存和帖子总数缓存
     *
     * @author ls
     * @date 2021/8/29 0:21
     */
    @PostConstruct
    public void init() {
        // 初始化帖子列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPostVo>>() {

                    @Override
                    public @Nullable List<DiscussPostVo> load(@NonNull String key) throws Exception {
                        if (StringUtils.isBlank(key)) {
                            throw new IllegalArgumentException("参数错误!");
                        }
                        String[] params = key.split(":");
                        if (params.length != 2) {
                            throw new IllegalArgumentException("参数错误!");
                        }
                        int startIndex = Integer.parseInt(params[0]);
                        int pageSize = Integer.parseInt(params[1]);

                        // 二级缓存：Redis -> mysql

                        logger.debug("load post list from DB");
                        return discussPostService.queryDiscussPostsFromDb(0, startIndex, pageSize, 1);
                    }
                });

        // 初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Override
                    public @Nullable Integer load(@NonNull Integer key) throws Exception {
                        logger.debug("load post rows from DB");
                        return discussPostMapper.queryDiscussPostRows(key);
                    }
                });
    }

    @Override
    public List<DiscussPostVo> queryDiscussPosts(int userId, int startIndex, int pageSize, int orderMode) {
        // 如果是查所有用户帖子且按帖子热度排序, 从缓存取数据
        if (userId == 0 && orderMode == 1) {
            return postListCache.get(startIndex + ":" + pageSize);
        }
        logger.debug("load post list from DB");
        return this.queryDiscussPostsFromDb(userId, startIndex, pageSize, orderMode);
    }

    @Override
    public List<DiscussPostVo> queryDiscussPostsFromDb(int userId, int startIndex, int pageSize, int orderMode) {
        List<DiscussPost> discussPosts = discussPostMapper.queryDiscussPosts(userId, startIndex, pageSize, orderMode);
        return discussPosts.stream().map(discussPost -> {
            DiscussPostVo discussPostVo = new DiscussPostVo();
            BeanUtils.copyProperties(discussPost, discussPostVo);
            discussPostVo.setUser(userService.queryUserById(discussPost.getUserId()));
            discussPostVo.setLikeCount(likeService.getEntityLikeCount(CommunityConstant.ENTITY_TYPE_POST, discussPost.getId()));
            return discussPostVo;
        }).collect(Collectors.toList());
    }

    @Override
    public int queryDiscussPostRows(int userId) {
        // 如果是查所有用户帖子数量, 从缓存取数据
        if (userId == 0) {
            if (postRowsCache.get(userId) == null) {
                return 0;
            }
            return postRowsCache.get(userId);
        }
        logger.debug("load post rows from DB");
        return discussPostMapper.queryDiscussPostRows(userId);
    }

    /**
     * 发布帖子
     *
     * @param discussPost
     */
    @Override
    public void addDiscussPost(DiscussPost discussPost) {
        if (discussPost == null) throw new IllegalArgumentException("发布失败,参数不能为空!");

        // 转义HTML标签
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
        // 过滤敏感词
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));

        discussPostMapper.addDiscussPost(discussPost);
    }

    @Override
    public DiscussPost queryDiscussPostById(int discussPostId) {
        return discussPostMapper.queryDiscussPostById(discussPostId);
    }

    @Override
    public void updateCommentCount(int id, int commentCount) {
        discussPostMapper.updateCommentCount(id, commentCount);
    }

    @Override
    public void updateStatus(int id, int status) {
        discussPostMapper.updateStatus(id, status);
    }

    @Override
    public void updateType(int id, int type) {
        discussPostMapper.updateType(id, type);
    }

    @Override
    public int updateScore(int id, double score) {
        return discussPostMapper.updateScore(id, score);
    }

}
